import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from './router'
import store from './store'
import { asyncRoutes } from '@/router'

const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  // to 到哪里去
  // from 从哪里来
  // next-必须执行的函数-不执行页面就会卡住 pending fullfiled rejected
  // next() 放过通行 login => dashboard => 顺利通行
  // next(false) 终止跳转 => login => dashboard => 留在login
  // next(地址) 转发地址 next("/test") login => dashboard => 跳到test
  // 不论什么场景下 next必须执行 否则就会页面空白
  nProgress.start() // 开启进度条
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      nProgress.done()
    } else {
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const newRoutes = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })
        store.commit('user/setRoutes', newRoutes)
        router.addRoutes([...newRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
        nProgress.done()
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nProgress.done()
    }
  }
})

router.afterEach(() => {
  nProgress.done()
})
